package com.wjs.CarolSecKill.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjs.CarolSecKill.mapper.OrderMapper;
import com.wjs.CarolSecKill.pojo.Order;
import com.wjs.CarolSecKill.pojo.SeckillGoods;
import com.wjs.CarolSecKill.pojo.SeckillOrder;
import com.wjs.CarolSecKill.pojo.User;
import com.wjs.CarolSecKill.service.IOrderService;
import com.wjs.CarolSecKill.service.ISeckillGoodsService;
import com.wjs.CarolSecKill.service.ISeckillOrderService;
import com.wjs.CarolSecKill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 
 *
 * @author wjs
 * @date 2022-09-03
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService iSeckillGoodsService;

    @Autowired
    private ISeckillOrderService iSeckillOrderService;

    @Override
    @Transactional
    public Order doSecKill(User user, GoodsVo goodsVo) {
        //秒杀商品表减库存
        SeckillGoods good = iSeckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));
        if(good.getStockCount()>0){
            boolean update = iSeckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count=stock_count-1").
                    eq("goods_id", good.getId()).
                    gt("stock_count", 0));
            if(!update){
                return null;
            }
        }else {
            return null;
        }
        //创建订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goodsVo.getGoodsPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        this.baseMapper.insert(order);
        //创建秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        iSeckillOrderService.save(seckillOrder);
        return order;
    }
}
